package com.jiangzhuolin.admin.service.impl;

import com.jiangzhuolin.admin.dao.UserRepository;
import com.jiangzhuolin.admin.pojo.Role;
import com.jiangzhuolin.admin.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 此类中实现操作数据库的相关逻辑，此处暂略
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(s);
        List<GrantedAuthority> authorityList = new ArrayList<>();
        getRoles(user, authorityList);
        // 返回一个 Spring Security 的认证对象
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorityList);
    }


    /**
     * 获取用户所属角色
     * @param user
     * @param list
     */
    private void getRoles(User user, List<GrantedAuthority> list){
        for (Role role : user.getRoles()) {
            // 权限如果前缀是ROLE_，security就会认为这是个角色信息，而不是权限，例如 ROLE_ADMIN 就是 ADMIN 角色，CAN_SEND 就是 CAN_SEND 权限
            list.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
    }
}
